/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;

import core.Book;
import core.Shop;
import core.User;
import core.comparators.BookComparator.BOOKCOMPARATORTYPE;
import core.comparators.ComparatorFactory;
import db.JDBC.core.BookJdbcDAOCore;
import db.JDBC.core.ShopJdbcDAOCore;
import db.xml.BookXML;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;

/**
 *
 * @author Anton
 */

public class BookBean
{
    private Long id;
    private Book book;
    private List<Book> books;

    @PostConstruct
    public void init()
    {
        String getId = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id");
        if(getId == null)
            return;
        id = new Long(getId);
        if(id != null)
            book = BookJdbcDAOCore.getInstance().getBookById(id);
        if(book != null)
        {
            String isbn10 = book.getIsbn10();
            String isbn13 = book.getIsbn13();
            Collection<Shop> shops = ShopJdbcDAOCore.getInstance().getAllShops();
            books = new ArrayList<Book>();

            if(shops != null)
            {
                for(Shop s : shops)
                {
                    String XMLSource = s.getXMLSource();
                    if(XMLSource != null)
                    {
                        BookXML bookXML = new BookXML(XMLSource);
                        Book returnBook = null;
                        if(isbn10 != null && isbn13 != null)
                        {
                            returnBook = bookXML.getBookByISBN10AndISBN13(isbn10, isbn13);
                        }
                        else if(isbn10 != null)
                        {
                            returnBook = bookXML.getBookByISBN10(isbn10);
                        }
                        else if(isbn13 != null)
                        {
                            returnBook = bookXML.getBookByISBN13(isbn13);
                        }
                        if(returnBook != null)
                            books.add(returnBook);
                    }
                }
                System.out.println("BOOKS!!!: " +   books);
                Collections.sort(books, ComparatorFactory.getBookComparator(BOOKCOMPARATORTYPE.PRICE, true));
            }
        }
    }

    public Long getId()
    {
        return id;
    }


    public Collection<Book> getBooks()
    {
        return books;
    }

    public Book getBook()
    {
        return book;
    }

    public boolean getContainsBooks()
    {
        return books.size() > 0;
    }
}
